package life.mahu.community.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import life.mahu.community.dto.GithubAndMayunUser;
import life.mahu.community.mapper.UserMapper;
import life.mahu.community.model.User;
import life.mahu.community.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private QuestionService questionService;

    //注册用户
    public Integer register(String username, String password, String name) {
        if (isExist(username))//判断用户名是否已经存在
            return 0;
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setName(name);
        user.setType(1);//注册都是默认账户状态为正常的1
        user.setFollowCount(0L);
        user.setBio("这个人很懒,他什么也没留下....");
        user.setAvatarUrl("default_head_image");
        user.setGmtCreate(System.currentTimeMillis());
        userMapper.insert(user);
        return 1;
    }

    //用户登录
    public Integer login(String accountId, Integer whithLogin, String token, String password, GithubAndMayunUser githubAndMayunUser) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        User user=new User();
        switch (whithLogin) {
            case 0://普通账户登录就用用户名来搜索
                if (!isExist(accountId))//如果用户名不存在
                    return 0;
                if (!checkPassword(accountId, password))//如果密码不准确
                    return 1;
                criteria.andUsernameEqualTo(accountId);
                break;
            case 1://github用户就用githubAccoundId来搜索
                criteria.andGithubAccountIdEqualTo(accountId);
                user.setGithubName(githubAndMayunUser.getName());
                user.setGithubAvatarUrl(githubAndMayunUser.getAvatarUrl());
                break;
            case 2://码云用户就用giteeAccoundId来搜索
                criteria.andGiteeAccountIdEqualTo(accountId);
                user.setGiteeName(githubAndMayunUser.getName());
                user.setGiteeAvatarUrl(githubAndMayunUser.getAvatarUrl());
                break;
        }
        List<User> users = userMapper.selectByExample(userExample);
        user.setToken(token);
        user.setGmtModified(System.currentTimeMillis());
        userExample.createCriteria()
                .andIdEqualTo(users.get(0).getId());
        userMapper.updateByExampleSelective(user, userExample);
        return 2;
    }

    //将用户的第三方登陆的用户信息和主用户绑定起来
    public void bind(String username, Long accountId, String htmlUrl,String accountName,String accountAvatar, String witchGit) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        User user=createUser(accountId, htmlUrl, accountName, accountAvatar, witchGit);
        Long id = users.get(0).getId();
        userExample.createCriteria()
                .andIdEqualTo(users.get(0).getId());
        userMapper.updateByExampleSelective(user, userExample);
    }

    //将用户的第三方登陆的用户信息和主用户绑定起来(by ID)
    public void bind(Long id, Long accountId, String htmlUrl,String accountName,String accountAvatar, String witchGit) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(id);
        User user=createUser(accountId, htmlUrl, accountName, accountAvatar, witchGit);
        userMapper.updateByExampleSelective(user, userExample);
    }

    //用于创建GitHubAndGiteeUser
    private User createUser(Long accountId, String htmlUrl, String accountName, String accountAvatar, String witchGit) {
        User user = new User();
        if ("github".equals(witchGit)) {//说明是github
            user.setGithubAccountId(String.valueOf(accountId));
            user.setGithubUrl(htmlUrl);
            user.setGithubName(accountName);
            user.setGithubAvatarUrl(accountAvatar);
        } else {//说明是码云
            user.setGiteeAccountId(String.valueOf(accountId));
            user.setGiteeUrl(htmlUrl);
            user.setGiteeName(accountName);
            user.setGiteeAvatarUrl(accountAvatar);
        }
        user.setGmtModified(System.currentTimeMillis());
        return user;
    }

    //检验用户名和密码是否匹配
    public boolean checkPassword(String username, String password) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        return passwordEncoder.matches(password,users.get(0).getPassword());
    }

    //判断该第三方登陆是否有绑定主用户(因为没有绑定的话就不会进入到数据库)
    public boolean isBind(String accountId, String type) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if ("github".equals(type))//如果是github登陆就根据githubId去查找对应的用户
            criteria.andGithubAccountIdEqualTo(accountId);
        else//如果是码云登陆就根据giteeId去查找对应的用户
            criteria.andGiteeAccountIdEqualTo(accountId);
        List<User> users = userMapper.selectByExample(userExample);
        return users.size() != 0;//如果根据第三方账号查询出来的数据没有userName就说明没有绑定主用户
    }
    //判断该用户名是否存在
    public boolean isExist(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        return userMapper.selectByExample(userExample).size() != 0;
    }


    //修改用户的特点字段信息
    public Integer updateMessage(Long id,String type,String newValue){
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andIdEqualTo(id);
        User user=new User();
        switch(type){
            case "name":
                user.setName(newValue);
                break;
            case "username":
                if(isExist(newValue))//判断用户名是否已经存在
                    return 0;
                user.setUsername(newValue);
                break;
            case "bio":
                user.setBio(newValue);
                break;
            case "avatar":
                user.setAvatarUrl(newValue);
                break;
        }
        userMapper.updateByExampleSelective(user, userExample);
        return 1;
    }

    //用于修改密码
    public Integer updatePassword(String username,String oldPassword,String newPassword){
        if(!checkPassword(username,oldPassword))
           return 0;
        else{
            UserExample userExample = new UserExample();
            userExample.createCriteria()
                    .andUsernameEqualTo(username);
            User user=new User();
            user.setPassword(passwordEncoder.encode(newPassword));
            userMapper.updateByExampleSelective(user, userExample);
            return 1;
        }
    }

    //获取用户的第三方绑定信息
    public List<GithubAndMayunUser> getEscrowAccount(User user){
        List<GithubAndMayunUser> escrowAccount=new ArrayList<>();
        if(user.getGithubAccountId()!=null){
            GithubAndMayunUser githubAndMayunUser=new GithubAndMayunUser();
            githubAndMayunUser.setId(Long.valueOf(user.getGithubAccountId()));
            githubAndMayunUser.setAvatarUrl(user.getGithubAvatarUrl());
            githubAndMayunUser.setName(user.getGithubName());
            githubAndMayunUser.setWitchGit(0);
            escrowAccount.add(githubAndMayunUser);
        }
        if(user.getGiteeAccountId()!=null){
            GithubAndMayunUser githubAndMayunUser=new GithubAndMayunUser();
            githubAndMayunUser.setId(Long.valueOf(user.getGiteeAccountId()));
            githubAndMayunUser.setAvatarUrl(user.getGiteeAvatarUrl());
            githubAndMayunUser.setName(user.getGiteeName());
            githubAndMayunUser.setWitchGit(1);
            escrowAccount.add(githubAndMayunUser);
        }
        return escrowAccount;
    }

    //将用户的第三方登陆信息解绑
    public Integer unbind(Long id,Integer witchGit){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(id);
        List<User> user= userMapper.selectByExample(userExample);
        User u=user.get(0);
        if(witchGit==0){
            u.setGithubAccountId(null);
            u.setGithubAvatarUrl(null);
            u.setGithubName(null);
            u.setGithubUrl(null);
        }else if(witchGit==1){
            u.setGiteeAccountId(null);
            u.setGiteeAvatarUrl(null);
            u.setGiteeName(null);
            u.setGiteeUrl(null);
        }
        userMapper.updateByExample(u,userExample);
        return 1;
    }
    public List<User> getUserList(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (user.getId() != null && user.getId() != 0) {
            criteria.andIdEqualTo(user.getId());
        }
        if (!(user.getName() == null  || "".equals(user.getName()))) {
            criteria.andNameLike(user.getName());
        }
        if (!(user.getUsername() == null || "".equals(user.getUsername()))) {
            criteria.andUsernameLike(user.getUsername());
        }
        if (user.getType() != null && user.getType() != 0) {
            criteria.andTypeEqualTo(user.getType());
        }

        return userMapper.selectByExample(userExample);
    }

    public PageInfo getUserListPage(User user, Integer page, Integer limit) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (user.getId() != null && user.getId() != 0) {
            criteria.andIdEqualTo(user.getId());
        }
        if (!(user.getName() == null  || "".equals(user.getName()))) {
            criteria.andNameLike("%" + user.getName() + "%");
        }
        if (!(user.getUsername() == null || "".equals(user.getUsername()))) {
            criteria.andUsernameLike("%" + user.getUsername() + "%");
        }
        if (user.getType() != null && user.getType() != 0) {
            criteria.andTypeEqualTo(user.getType());
        }
        PageHelper.startPage(page, limit);
        List<User> userList = userMapper.selectByExample(userExample);
        return new PageInfo<User>(userList);
    }

    public User getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public Boolean insertUser(User user) {
        if(user.getAvatarUrl()!=null)
            user.setAvatarUrl("default_head_image");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setGmtCreate(System.currentTimeMillis());
        user.setGmtModified(System.currentTimeMillis());
        int insert = userMapper.insert(user);
        return insert>0?true:false;
    }

    public Boolean updateUserByUserId(User user) {
        User loseUser = userMapper.selectByPrimaryKey(user.getId());
        if(user.getPassword()!=null)
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setGmtModified(System.currentTimeMillis());
        user.setToken(loseUser.getToken());
        user.setGmtCreate(loseUser.getGmtCreate());
        int update = userMapper.updateByPrimaryKey(user);
        return update>0?true:false;
    }

    public Boolean delUserById(Long id) {
        int delUser = userMapper.deleteByPrimaryKey(id);
        return delUser>0?true:false;
    }
}
